package com.${sysEname}.controller;

import com.apache.api.api.ApiService;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.client.LogClient;
import com.apache.client.UctCoreClient;
import com.apache.ius.common.CommonUtils;
import com.apache.ius.common.annotion.AnnotationUtil;
import com.apache.ius.controller.SuperApiAction;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.passport.common.DesUtils;
import com.apache.passport.entity.Token;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.*;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import com.apache.uct.common.entity.Role;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 平台自动生成的统一开放第三方相关的api接口controller类
 * /api/*已配置在白名单内
 * 请求地址参考：http://127.0.0.1:网关端口/${sysEname}/api/***
 * 其他方法，请自行补充
 */
@Controller
@RequestMapping({"/api/"})
public class ApiAction extends SuperApiAction {

    private Logger log = Logger.getLogger(getClass());



    //登录
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        ResultMsg msg = new ResultMsg("F", "登录失败");
        //Map<String, String> params = this.getParameterMap(request);
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        log.info("client request params-->" + params);
        Map<String, Object> maps = new HashMap<String, Object>();
        String username = params.get("username");//支持传入：用户账号、手机号、邮箱
        String password = params.get("password");
        String smsCode = params.get("smsCode");//短信验证码
        String source = StrUtil.doNull(params.get("source"), "");//登录来源：weixin,app
        String openId = StrUtil.doNull(params.get("openId"), "");//微信openId
        String type = StrUtil.doNull(params.get("type"), "1");//1:默认账号、手机号、邮箱+密码方式，2、手机号+验证码

        //判断类型，以备校验
        switch (type) {
            case "1"://账号、手机号、邮箱+密码
                if (StrUtil.isNull(username) || StrUtil.isNull(password)) {
                    this.gotoErrorPage(request, response, "登录信息不能为空");
                    return;
                }
                break;
            case "2"://手机号+短信验证码
                String mobile = username;
                if (StrUtil.isNull(mobile) || StrUtil.isNull(smsCode)) {
                    this.gotoErrorPage(request, response, "手机号码或验证码不能为空");
                    return;
                }
                String smsCode_old = String.valueOf(CommonUtils.getCache("mobile_obj_" + mobile));
                log.info("smsCode validator -> [old->" + smsCode_old + "]=[input->" + smsCode + "]");
                if (!smsCode.equals(smsCode_old)) {
                    this.gotoErrorPage(request, response, "短信验证码有误");
                    return;
                } else {
                    CommonUtils.removeCache("mobile_obj_" + mobile);//验证成功，移除
                }
                maps.put("isCheckPass", "F");//告知sso不验证密码
                break;
        }

        //查询用户是否存在，判断是否是否满足当前的登录入口。
        Map<String, Object> uct_whereMap = new HashMap<>();
        if(checkMobile(username)){//登录账号是手机号
            //按照手机号和，来源类型查询用户是否存在，
            uct_whereMap.put("uctUser.w_mobile", username);
        }else{
            uct_whereMap.put("uctUser.w_userEname", username);
        }
        ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("plateform", "list", "s_uctUser", uct_whereMap);
        Map<String, Object> resultMap = super.getResultEntityData(resultEntity1);
        if ("T".equals(resultMap.get("flag"))) {
            List<DataMap> userList = (ArrayList<DataMap>) resultMap.get("rows");
            log.info("根据["+username+"]查找到用户个数["+userList.size()+"]");
            if(userList.size()==0){
                msg = new ResultMsg("F", "F03");//账号不存在，提示： 登录号或者密码有误
                gotoErrorPage(request, response, msg.getMsg());
                return;
            }else{
                //用户存在则获取第一个满足条件的用户userEname
                DataMap userInfo = userList.get(0);
                String mobile_userEname = String.valueOf(userInfo.get("userEname"));
                String userType = String.valueOf(userInfo.get("userType"));
                String auditStatus = String.valueOf(userInfo.get("auditStatus"));
                log.info("当前可在登录的用户userEname["+mobile_userEname+"]");
                username=mobile_userEname;

                if ("10".equals(auditStatus)) {
                    msg = new ResultMsg("F", "F01");//此用户正在审核中
                    gotoErrorPage(request, response, msg.getMsg());
                    return;
                }
                if ("manager".equals(userType)) {
                    msg = new ResultMsg("F", "F04");//此用户暂无权限
                    gotoErrorPage(request, response, msg.getMsg());
                    return;
                }
                if ("90".equals(auditStatus)) {
                    msg = new ResultMsg("F", "F07");//此用户未审核通过
                    gotoErrorPage(request, response, msg.getMsg());
                    return;
                }
            }
        }else{
            msg = new ResultMsg("F", "F03");//账号不存在，提示： 登录号或者密码有误
            gotoErrorPage(request, response, msg.getMsg());
            return;
        }

        //准备参数请求sso进行登录验证。
        maps.put("userEname", username);
        maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
        maps.put("userPass", password);
        maps.put("sysEname", ToolsUtil.getInstance().getValueByKey("sysEname"));
        maps.put("addressIP", maps.get("Client-IP"));
        //请求sso返回登录结果
        JSONObject resObj = getLoginJsonObject(request, response, maps);

        this.outputJson(resObj.toString(), response, "");
//        if (!ToolsUtil.isEmpty(msg)) {
//            JSONObject obj = JSONObject.fromObject(msg);
//            this.outputJson(obj.toString(), response, "");
//        }
    }
    /**
     * 判断是否是手机号格式
     * @param mobile
     * @return
     */
    private static boolean checkMobile(String mobile) {
        String regex = "^\\d{11}$";
        Pattern pattern = Pattern.compile(regex);
        if(StrUtil.isNull(mobile)){
            return  false;
        }else{
            return pattern.matcher(mobile).matches();
        }
    }
    /**
     * sso登录封装方法
     */
    private JSONObject getLoginJsonObject(HttpServletRequest request, HttpServletResponse response, Map<String, Object> maps) {
        ResultMsg msg = new ResultMsg("F", "登录失败");
        JSONObject resObj = new JSONObject();
        String login_username = String.valueOf(maps.get("userEname"));
        ResultEntity entity = LoadRpcService.service().doServiceClient("ssoService", "outSideSocketLoginService", maps,
                PortalPubFactory.getInstance().getRpcInfo("sso"));
        if (entity != null && ("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof String) {
                String userMsg = String.valueOf(entity.getMessage());
                log.error("登录异常提示：" + userMsg);
                if (userMsg.indexOf("用户已停用") > -1) {
                    msg = new ResultMsg("F", "F02");//您的账户已停止登录
                } else if (userMsg.indexOf("删除") > -1) {
                    msg = new ResultMsg("F", "F02");//您的账户已关闭登录操作
                } else {
                    if ("密码错误".equals(userMsg) || "用户不存在".equals(userMsg)) {
                        msg = new ResultMsg("F", "F03");//登录号或者密码有误
                    } else {
                        msg = new ResultMsg("F", userMsg);
                    }
                }
                resObj = JSONObject.fromObject(msg);
            } else {
                //仓储cookie
                Token token = (Token) entity.getEntity();
                Cookie cookie = new Cookie(ToolsUtil.getInstance().getValueByKey("cookieName"),
                        token.getTokenId());
                cookie.setPath("/");
                cookie.setMaxAge(-1);
                Cookie ucsso = new Cookie("_uc.sso",
                        DesUtils.getInstance().decrypt(token.getUserEname()));
                ucsso.setPath("/");
                ucsso.setMaxAge(-1);
                response.addCookie(cookie);
                response.addCookie(ucsso);
                request.getSession().removeAttribute("loginUser");
                request.getSession().removeAttribute("tokenId");
                request.getSession().setAttribute("tokenId", token.getTokenId());
                log.info("[" + login_username + "]登录成功！");
                //剔除loginInfo，解密email，userEname，mobile传明文
                JsonConfig jc = new JsonConfig();
                String config[] = {"loginInfo"};
                jc.setExcludes(config);
                String token_email = token.getEmail();
                String token_mobile = token.getMobile();
                String token_userEname = token.getUserEname();
                token.setEmail(DesUtils.getInstance().decrypt(token_email));
                token.setMobile(DesUtils.getInstance().decrypt(token_mobile));
                token.setUserEname(DesUtils.getInstance().decrypt(token_userEname));
//                msg = new ResultMsg("T", JSONObject.fromObject(token, jc).toString());
                msg = new ResultMsg("T", "登录成功");
                resObj = JSONObject.fromObject(msg, jc);

                //记录日志
                Map<String, Object> logMap = new HashMap<String, Object>();
                logMap.put("logOperationType", "login");
                logMap.put("logClassName", User.class.getName());
                logMap.put("logIp", maps.get("Client-IP"));
                logMap.put("log_userEname", token.getUserEname());
                log.info("登录成功日志：" + logMap);
                LogClient.getInstance().execute(logMap);//添加日志

                //存储session
                if ("T".equals(msg.getFlag())) {
                    JSONObject jb = JSONObject.fromObject(token);
                    Map<String, Object> map = (Map) jb;
                    LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(String.valueOf(map.get("userEname")),
                            String.valueOf(map.get("tokenId")));
                    if (loginUser != null) {
                        jb.put("sysFlag", loginUser.getSysFlag());
                        jb.put("actMap", loginUser.getActMap());
                        String actJsonStr = StrUtil.doNull(loginUser.getActJsonStr(), "");
                        jb.put("actJsonStr", actJsonStr);
                        String actFnmStr = "";
                        if (!StrUtil.isNull(actJsonStr)) {
                            JSONArray actJsonArray = JSONArray.fromObject(actJsonStr);
                            if (actJsonArray.size() > 0) {
                                for (int i = 0; i < actJsonArray.size(); i++) {
                                    JSONObject actJson = (JSONObject) actJsonArray.getJSONObject(i);
                                    if (i == 0) {
                                        actFnmStr += actJson.getString("fnm");
                                    } else {
                                        actFnmStr += "," + actJson.getString("fnm");
                                    }
                                }
                            }
                        }
                        jb.put("actFnmStr", actFnmStr);
                        User user = loginUser.getUser();
                        if (user != null) {
                            jb.put("userRemark", StrUtil.doNull(user.getUserRemark(), ""));
                            jb.put("auditStatus", StrUtil.doNull(user.getAuditStatus(), ""));
                            jb.put("managerType", StrUtil.doNull(user.getManagerType(),""));
                            jb.put("recordType", StrUtil.doNull(user.getRecordType(),""));
                            jb.put("district", StrUtil.doNull(user.getDist(),""));
                            jb.put("auditText", StrUtil.doNull(user.getAuditText(), ""));
                            jb.put("userSex", StrUtil.doNull(user.getUserSex(), ""));
                            jb.put("userStatus", user.getUserStatus());
                            jb.put("userTitle", StrUtil.doNull(user.getUserTitle(), ""));
                            jb.put("address", StrUtil.doNull(user.getAddress(), ""));
                            jb.put("appId", StrUtil.doNull(user.getAppUid(), ""));
                            jb.put("userScore", user.getUserScore());
                            jb.put("certType", StrUtil.doNull(user.getCertType(), ""));
                            jb.put("certNo", StrUtil.doNull(user.getCertNo(), ""));
                            jb.put("orgId", StrUtil.doNull(user.getOrgId(), ""));
                            jb.put("orgEname", StrUtil.doNull(user.getOrgEname(), ""));
                            jb.put("province", StrUtil.doNull(user.getProvince(), ""));
                            jb.put("city", StrUtil.doNull(user.getCity(), ""));
                            jb.put("deptId", StrUtil.doNull(user.getDeptId(), ""));
                            jb.put("dataOrgIds", StrUtil.doNull(loginUser.getDataOrgIds(), ""));//存储机构权限
                        }
                        request.getSession().setAttribute("loginUser", loginUser);
                        Map<String, Object> roleMap = new HashMap();
                        roleMap.put("userEname", loginUser.getUserEname());
                        ResultEntity roleEntity = UctCoreClient.searchRoleByReflect(roleMap);
                        jb.put("roles",roleEntity.getEntity());
                    }
                    resObj.put("loginUser", jb);
                    request.getSession().setAttribute("loginUser", loginUser);
                }
            }
        }
        log.info("[" + login_username + "]登录结果：" + resObj.toString());
        return resObj;
    }

    //文件上传,支持上传至oss
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public void uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("flag", "F");
        final long minLen = 1024 * 1024 * 5; // 5M
        final long maxLen = 1024 * 1024 * 1024; // 1G
        long starTime = new Date().getTime();
        Map<String, String> params = this.getParameterMap(request);// this.getParameterMapByJson(request,requestBody);

        // 如果文件不为空，写入上传路径，进行文件上传
        log.info("\n");
        if (!file.isEmpty()) {
            log.info("client request params-->" + params);
            String fileContentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            long fileSize = file.getSize();

            log.info("File upload start...");
            log.info("File contentType-> " + fileContentType);

            //1、从本地config文件读取配置
            String localFileName = "config.properties";
            String fileUploadDirectory = ToolsUtil.getInstance().getLocalByKey(localFileName, "UPLOAD_DIRECTORY");//获取文件需要上传到的根目录
            String fileDownloadUrl = ToolsUtil.getInstance().getLocalByKey(localFileName, "DOWNLOAD_URL");//获取文件需要下载的根目录地址
            String fileAllowType = ToolsUtil.getInstance().getLocalByKey(localFileName, "ALLOW_TYPE");//允许上传的文件类型
            String fileMaxLength = ToolsUtil.getInstance().getLocalByKey(localFileName, "FILE_MAX_LENGTH");//文件大小最大值
            if (StrUtil.isNull(fileUploadDirectory) || StrUtil.isNull(fileDownloadUrl)) {
                log.error(localFileName + "配置文件缺少[UPLOAD_DIRECTORY、DOWNLOAD_URL、ALLOW_TYPE、FILE_MAX_LENGTH]等相关配置");
                resultMap.put("msg", "服务端缺少相关配置");
                JSONObject obj = JSONObject.fromObject(resultMap);
                this.outputJson(obj.toString(), response, "");
                return;
            }
            String FILE_MAX_LENGTH = StrUtil.doNull(fileMaxLength, String.valueOf(maxLen));//单位B
            String File_ALLOW_TYPE = fileAllowType;
            long fimaxLength = Long.valueOf(FILE_MAX_LENGTH).longValue();
            log.info("Config FILE_MAX_LENGTH-> " + FILE_MAX_LENGTH + "=" + getFileSize(fimaxLength));
            log.info("Config ALLOW_TYPE-> " + File_ALLOW_TYPE);

            //2、配置上传参数
            String uploadRoot = fileUploadDirectory + "/atta/"; //获取文件需要上传到的根目录
            String downloadRoot = fileDownloadUrl + "/atta/";//获取文件需要下载的根目录
            String nowDataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());// + "/";
            String fileTypes = StrUtil.doNull(params.get("upload_fileTypes"), File_ALLOW_TYPE);
            String sysEname = StrUtil.doNull(params.get("upload_sysName"), CommonUtils.getSysEname());
            String uploadFolder = StrUtil.doNull(params.get("upload_folder"), "");//自定义业务类型文件夹
            String confData = StrUtil.doNull(params.get("confData"), "");//其他配置参数json格式的字符串
            log.info("File request confData->  " + confData);
            String waterFlag = "F", waterText = "", waterType = "";//水印配置参数
            String ossFlag = "F",ossReLocalFlag="F";//是否上传至阿里云的oss,上传成功后是否删除本地文件
            if (!StrUtil.isNull(confData)) {
                JSONObject jsonConf = JSONObject.fromObject(confData);
                waterFlag = StrUtil.doNull(String.valueOf(jsonConf.get("waterFlag")), "F");//是否添加水印
                waterText = StrUtil.doNull(String.valueOf(jsonConf.get("waterText")), "水印文字LOGO");//是否水印文字
                waterType = StrUtil.doNull(String.valueOf(jsonConf.get("waterType")), "1");//水印方式：1=普通右下角，2=45°斜铺

                ossFlag = StrUtil.doNull(String.valueOf(jsonConf.get("ossFlag")), "F");//是否上传至阿里云的oss
                ossReLocalFlag = StrUtil.doNull(String.valueOf(jsonConf.get("ossReLocalFlag")), "F");//oss上传成功后是否删除本地文件
            }

            log.info("File request upload_fileTypes-> " + fileTypes);
            log.info("File request sysEname-> " + sysEname);
            String uploadPath = uploadRoot + sysEname + "/";

            if (!StrUtil.isNull(uploadFolder)) {
                uploadPath += uploadFolder + "/";
            }
            uploadPath += nowDataStr;// 上传目录
            String fileSizeStr = getFileSize(fileSize);
            log.info("File name-> [" + fileName + "] | size[" + fileSizeStr + "]");

            //3、判断上传规则
            if (fileSize > fimaxLength) {
                resultMap.put("msg", "服务端暂不支持文件大小超过" + getFileSize(fimaxLength));
                log.error("File size-> 服务端暂不支持文件大小超过" + getFileSize(fimaxLength));
                JSONObject obj = JSONObject.fromObject(resultMap);
                this.outputJson(obj.toString(), response, "");
                return;
            }

            //4、执行上传
            log.info("File directory-> " + uploadPath);
            // 构建上传文件的存放路径，获取上传的文件名称，并结合存放路径，构建新的文件名称
            String filename = file.getOriginalFilename();
            File filepath = new File(uploadPath, filename);//创建新文件
            if (!filepath.getParentFile().exists()) { // 判断路径是否存在，不存在则新创建一个
                filepath.getParentFile().mkdirs();
            }
            //获取文件扩展名后缀
            String nameEx = (filename.lastIndexOf('.') >= 0) ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase() : "";
            String wrFileName = String.valueOf(System.currentTimeMillis()) + "." + nameEx;//指定文件新名
            String fileNewPath = uploadPath + File.separator + wrFileName;//新文件上传全路径
            String fileNewPathMin = uploadPath + File.separator +  String.valueOf(System.currentTimeMillis()) + "_min." + nameEx;//压缩图路径
            File fileNew = new File(fileNewPath);
            file.transferTo(fileNew);// 将上传文件保存到目标文件目录
            log.info("File is uploading path-> " + fileNewPath);

            //5、准备文件访问/下载地址内容及返回参数
            String downloadPath = downloadRoot + sysEname + File.separator;
            if (!StrUtil.isNull(uploadFolder)) {
                downloadPath += uploadFolder + File.separator;
            }
            downloadPath += nowDataStr + File.separator + wrFileName;
            downloadPath = downloadPath.replaceAll("\\\\", "/");
            log.info("File download full path-> " + downloadPath);

            resultMap.put("flag", "T");
            resultMap.put("msg", "上传成功");
            resultMap.put("murl", downloadPath);
            resultMap.put("filePath", uploadPath + File.separator);
            resultMap.put("fileNameNew", wrFileName);
            resultMap.put("fileName", fileName);
            resultMap.put("fileSize", fileSizeStr);
            resultMap.put("fileType", nameEx);
            resultMap.put("sysEname", sysEname);
            resultMap.put("ossFlag", ossFlag);

            long timeLong = (new Date().getTime() - starTime);
            resultMap.put("timeLong", timeLong + "ms");
            log.info("File upload result-->" + resultMap);
        }
        if (!ToolsUtil.isEmpty(resultMap)) {
            JSONObject obj = JSONObject.fromObject(resultMap);
            this.outputJson(obj.toString(), response, "");
        }
    }

    //发送短信
    @RequestMapping(value = "/sendSmsCode", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void sendSmsCode(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        ResultMsg msg = new ResultMsg("F", "短信发送失败");
        //Map<String, String> params = this.getParameterMap(request);
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        log.info("client request params-->" + params);
        String type = params.get("type");
        String mobile = params.get("mobile");
        if (StrUtil.isNull(mobile)) {
            this.gotoErrorPage(request, response, "手机号码不能为空！");
            return;
        }

        String codeNo = UUIDUtil.getRandomStr("1", 6, 97);//验证码
        Map<String, String> resultSmsMap = CommonUtils.sendSmsByCache(mobile, codeNo);
        String resultCode = resultSmsMap.get("code");
        if ("OK".equals(resultCode)) {
            String content = "验证码已发送至您的手机上";
            if ("F".equals(resultSmsMap.get("sms_code_start"))) {
                content += "[" + codeNo + "]";
            }
            msg = new ResultMsg("T", content);
            CommonUtils.addCache("mobile_obj_" + mobile, codeNo, Integer.parseInt(StrUtil.doNull(CommonUtils.getConfigVal("expireTime")    ,"1200")));//5-6分钟
        }


        String userEmail = params.get("userEmail");
        if(StrUtil.isNotNull(userEmail)){
            log.info("-");
            log.info("准备发送邮件验证码："+userEmail);
//            Map<String, String> resultSmsMap2 = MailUtil.sendMail(userEmail,"","您的验证码为："+codeNo);
        }

        if (!ToolsUtil.isEmpty(msg)) {
            JSONObject obj = JSONObject.fromObject(msg);
            this.outputJson(obj.toString(), response, "");
        }
    }

    //验证手机号是否存在
    @RequestMapping(value = "/checkMobileExist", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void checkMobileExist(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        ResultMsg msg = new ResultMsg("F", "注册失败");
        //Map<String, String> params = this.getParameterMap(request);
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        String source = StrUtil.doNull(params.get("source"), "");//登录来源：weixin,app
        int userScore = 20;
        switch (source.toLowerCase()) {
            case "weixin":
                userScore = 20;
                break;
            case "app":
                userScore = 30;
                break;
        }

        log.info("client request params-->" + params);
        String mobile = params.get("mobile");
        if (StrUtil.isNull(mobile)) {
            this.gotoErrorPage(request, response, "手机号不能为空！");
            return;
        }
        Map<String, Object> whereMap = new HashMap<>();
        whereMap.put("uctUser.w_mobile", mobile);
//        whereMap.put("uctUser.w_userScore", userScore);
        ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("plateform", "count", "s_uctUser", whereMap);
        Map<String, Object> resultMap = super.getResultEntityData(resultEntity1);
        if ("T".equals(resultMap.get("flag")) && Long.parseLong(String.valueOf(resultMap.get("result"))) > 0) {
            CommonUtils.removeCache("mobile_obj_" + mobile);//验证成功，移除
            this.gotoErrorPage(request, response, "手机号码已存在！");
            return;
        }
        msg = new ResultMsg("T", "验证成功，手机号不存在！");
        JSONObject obj = JSONObject.fromObject(msg);
        this.outputJson(obj.toString(), response, "");
    }


    //验证手机短信验证码
    @RequestMapping(value = "/checkSmsCode", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void checkSmsCode(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        ResultMsg msg = new ResultMsg("F", "注册失败");
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        log.info("client request params-->" + params);
        String mobile = params.get("mobile");
        String smsCode = params.get("smsCode");//短信验证码
        if (StrUtil.isNull(mobile) || StrUtil.isNull(mobile)) {
            this.gotoErrorPage(request, response, "手机号或短信验证码不能为空！");
            return;
        }

        String smsCode_old = String.valueOf(CommonUtils.getCache("mobile_obj_" + mobile));
        log.info("smsCode validator -> [old->" + smsCode_old + "]=[input->" + smsCode + "]");
        if (!smsCode.equals(smsCode_old)) {
            this.gotoErrorPage(request, response, "短信验证码有误");
            return;
        } else {
            CommonUtils.removeCache("mobile_obj_" + mobile);//验证成功，移除
        }
        msg = new ResultMsg("T", "短信验证码验证成功！");
        JSONObject obj = JSONObject.fromObject(msg);
        this.outputJson(obj.toString(), response, "");
    }

    //用户注册
    @RequestMapping(value = "/userRegister", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void userRegister(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        log.info("client request params-->" + params);
        String smsCode = params.get("uctUser.smsCode");//短信验证码
        String syncLogin = StrUtil.doNull(params.get("syncLogin"), "F");//是否同步登录
        String wUserId = StrUtil.doNull(params.get("uctUser.w_userId"), "");//区分是第一次注册新增，还是审核退回修改提交。
        String userEname = "";
        boolean isAdd = true;
        if (!StrUtil.isNull(wUserId)) {
            isAdd = false;
            userEname = StrUtil.doNull(params.get("uctUser.userEname"), "");
        }
        log.info("user register info is add -> " + isAdd);
        log.info("user register info is sync login -> " + syncLogin);

        String openId = StrUtil.doNull(params.get("uctUser.appUid"), "");//openId
        String userCname = params.get("uctUser.userCname");//nickName
        String mobile = params.get("uctUser.mobile");//
        String password = params.get("uctUser.userPass");
        String userType = params.get("uctUser.userType");//用户类型：1=app兼职人员，2=微信用户

        if (isAdd) {
            //注册新增
            if (StrUtil.isNull(openId)) {
                this.gotoErrorPage(request, response, "openId不能为空！");
                return;
            }
            if (StrUtil.isNull(userType) || StrUtil.isNull(userCname) || StrUtil.isNull(password)) {
                this.gotoErrorPage(request, response, "必填项不能为空！");
                return;
            }
            String userNoRandom = UUIDUtil.getRandomStr("3", 8, 97);//自动生成默认登录英文名称;
            userEname = "wx_" + userNoRandom;
            //验证是否重复
            Map<String, Object> whereMap = new HashMap<>();
            whereMap.put("uctUser.w_appUid", openId);

            ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("plateform", "obj", "s_uctUser", whereMap);
            Map<String, Object> resultMap = super.getResultEntityData(resultEntity1);
            if ("T".equals(resultMap.get("flag")) && resultMap.get("result")!=null) {
                if("F".equals(syncLogin)){
                    this.gotoErrorPage(request, response, "openId已存在！");
                    return;
                }else{
                    log.info("openId["+openId+"]已存在.开始发起同步登录...");
                    DataMap userInfo = (DataMap) resultMap.get("result");
                    String login_userEname = String.valueOf(userInfo.get("userEname"));
                    //同步发起登录
                    //准备参数请求sso进行登录验证。
                    Map<String, Object> maps = new HashMap<String, Object>();
                    maps.put("isCheckPass", "F");//告知sso不验证密码
                    maps.put("userEname", login_userEname);
                    maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
                    maps.put("userPass", password);
                    maps.put("sysEname", ToolsUtil.getInstance().getValueByKey("sysEname"));
                    maps.put("addressIP", maps.get("Client-IP"));
                    //请求sso返回登录结果
                    JSONObject resObj = getLoginJsonObject(request, response, maps);
                    this.outputJson(resObj.toString(), response, "");
                    return;
                }

            }
        } else {
            //注册修改
        }

        //准备数据
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.putAll(params);
        String sysEname = CommonUtils.getSysEname();
        String createTime = DateUtils.Now.fmt_yyyyMMdd_HHmmss();
        paramsMap.put("uctUser.sysEname", sysEname);
        paramsMap.put("uctUser.delStatus", "0");//是否系统机构用户 0
        paramsMap.put("uctUser.userSore", "20");
        if(StrUtil.isNotNull(openId)){
            paramsMap.put("uctUser.regSource", "weixin");
        }
        paramsMap.put("uctUser.userStatus", "1");//启用状态
        paramsMap.put("uctUser.userEname", userEname);
        log.info("[" + userEname + "][" + userCname + "][" + mobile + "]开始注册【新增】操作...");
        //保存uctUser操作
        ResultEntity resultEntity = IusPluginUtil.getInstance().saveInvoke("plateform", "i_uctUser", paramsMap);
        Map<String, Object> resultMap = super.getResultEntityData(resultEntity);
        if ("F".equals(resultMap.get("flag"))) {
            this.gotoErrorPage(request, response, "操作失败！");
            return;
        }
        String userId = "";
        if (isAdd) {
            //注册新增
            Map<String, String> idsMap = (Map) resultMap.get("ids");
            userId = String.valueOf(idsMap.get("uctUser_userId"));
        }
        if (isAdd) {
            //注册新增
            Map<String, String> idsMap = (Map) resultMap.get("ids");
            userId = String.valueOf(idsMap.get("uctUser_userId"));
        }
        Map<String, Object> resMap = new HashMap<String,Object>();
        resMap.put("flag", "T");
        resMap.put("userId", userId);
        resMap.put("userEname",userEname);
        resMap.put("msg", "注册成功");
        JSONObject obj = JSONObject.fromObject(resMap);
        log.info("操作执行结果：" + obj);
        if("T".equals(syncLogin)){
            log.info("注册成功.开始发起同步登录...");
            //同步发起登录
            //准备参数请求sso进行登录验证。
            Map<String, Object> maps = new HashMap<String, Object>();
            maps.put("isCheckPass", "F");//告知sso不验证密码
            maps.put("userEname", userEname);
            maps.put("Client-IP", StrUtil.doNull(params.get("Client-IP"), RequestTools.getIp(request)));
            maps.put("userPass", password);
            maps.put("sysEname", ToolsUtil.getInstance().getValueByKey("sysEname"));
            maps.put("addressIP", maps.get("Client-IP"));
            //请求sso返回登录结果
            JSONObject resObj = getLoginJsonObject(request, response, maps);
            this.outputJson(resObj.toString(), response, "");
        }else{
            this.outputJson(obj.toString(), response, "");
        }
    }

    /**
     * 密码找回、密码修改
     * type=1:密码找回，2：密码修改
     */
    @RequestMapping(value = "/userPass", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public void userPass(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> requestBody) throws Exception {
        ResultMsg msg = new ResultMsg("F", "注册失败");
        //Map<String, String> params = this.getParameterMap(request);
        Map<String, String> params = this.getParameterMapByJson(request, requestBody);
        log.info("client request params-->" + params);
        String smsCode = params.get("smsCode");//短信验证码
        String mobile = params.get("mobile");
        String oldPass = params.get("oldPass");
        String newPass = params.get("newPass");
        String openId = params.get("openId");
        String source = params.get("source");//来源
        String type = params.get("type");//根据手机号= 1:密码找回，2：密码修改
        switch (type) {
            case "1":
                if (StrUtil.isNull(mobile) || StrUtil.isNull(newPass) || StrUtil.isNull(smsCode)) {
                    this.gotoErrorPage(request, response, "必填项不能为空！");
                    return;
                }
                if ("weixin".equals(source.toLowerCase())) {
                    if (StrUtil.isNull(openId)) {
                        this.gotoErrorPage(request, response, "缺少openId参数！");
                        return;
                    }
                }
                break;
            case "2":
                if (StrUtil.isNull(mobile) || StrUtil.isNull(newPass) || StrUtil.isNull(oldPass)) {
                    this.gotoErrorPage(request, response, "必填项不能为空！");
                    return;
                }
                break;
        }
        int userScore = 20;
        switch (source.toLowerCase()) {
            case "weixin":
                userScore = 20;
                break;
            case "app":
                userScore = 30;
                break;
        }

        Map<String, Object> whereMap = new HashMap<>();
        whereMap.put("uctUser.w_mobile", mobile);
        whereMap.put("uctUser.w_userScore", userScore);
        ResultEntity resultEntity1 = IusPluginUtil.getInstance().select("plateform", "obj", "s_uctUser", whereMap);
        Map<String, Object> resultMap = super.getResultEntityData(resultEntity1);
        if ("F".equals(resultMap.get("flag")) && StrUtil.isNull(String.valueOf(resultMap.get("result")))) {
            CommonUtils.removeCache("mobile_obj_" + mobile);//验证成功，移除
            this.gotoErrorPage(request, response, "手机号不已存在！");
            return;
        }
        DataMap userInfo = (DataMap) resultMap.get("result");
        if ("weixin".equals(source) && !StrUtil.isNull(openId)) {
            String appUid = String.valueOf(userInfo.get("appUid"));
            if (!openId.equals(appUid)) {
                log.info("手机号[" + mobile + "]和该微信用户不匹配-[openId=" + openId + "]-[appUid=" + appUid + "]");
                this.gotoErrorPage(request, response, "手机号和该微信用户不匹配！");
                return;
            }
        }
        String userCname = String.valueOf(userInfo.get("userCname"));
        String userId = String.valueOf(userInfo.get("userId"));
        switch (type) {
            case "1":
                //密码找回时，需要验证短信验证码
                String smsCode_old = String.valueOf(CommonUtils.getCache("mobile_obj_" + mobile));
                log.info("smsCode validator -> [old->" + smsCode_old + "]=[input->" + smsCode + "]");
                if (!smsCode.equals(smsCode_old)) {
                    this.gotoErrorPage(request, response, "短信验证码有误");
                    return;
                } else {
                    CommonUtils.removeCache("mobile_obj_" + mobile);//验证成功，移除
                }
                break;
            case "2":
                //密码修改时，判断输入的旧密码必须=存的密码；
                if (!oldPass.equals(String.valueOf(userInfo.get("userPass")))) {
                    this.gotoErrorPage(request, response, "原密码输入有误！");
                    return;
                }
                break;
        }

        //准备数据
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        log.info("开始修改用户密码[" + userCname + "]...");
        paramsMap.put("uctUser.w_userId", userId);
        paramsMap.put("uctUser.userPass", newPass);

        //保存操作
        ResultEntity resultEntity = IusPluginUtil.getInstance().saveInvoke("plateform", "u_uctUser", paramsMap);
        resultMap = super.getResultEntityData(resultEntity);
        log.info("执行结果：" + resultMap);
        if ("F".equals(resultMap.get("flag"))) {
            this.gotoErrorPage(request, response, "操作失败！");
            return;
        }
        resultMap.put("msg", "密码修改成功");
        JSONObject obj = JSONObject.fromObject(resultMap);
        this.outputJson(obj.toString(), response, "");
    }

    @Autowired(required = false)
    @Qualifier("${sysEname}Service")
    private ApiService ${sysEname}Service;//注入本工程bean

    //初始化方法
    @ModelAttribute
    public void populateModel() throws Exception {
        if (this.iusService == null) {
            this.setIusService(${sysEname}Service);//注入本工程bean
        }
        if (!AnnotationUtil.isScanning) {
            AnnotationUtil.getInstance().loadCalssBean("com.apache.ius");
        }
    }
    private static String getFileSize(long leng) {
        String re = String.valueOf(leng);
        if (leng >= (1024 * 1024 * 1024)) {
            re = NumberUtils.divide(leng, (1024 * 1024 * 1024), 0) + "G";
        } else if (leng >= (1024 * 1024)) {
            re = NumberUtils.divide(leng, (1024 * 1024), 0) + "M";
        } else if (leng >= (1024)) {
            re = NumberUtils.divide(leng, (1024), 0) + "KB";
        } else {
            re = leng + "";
        }
        return re;
    }

    /**
     * 服务器时间戳
     * @param request
     * @return
     */
    @RequestMapping(value = "/time", method = { RequestMethod.GET})
    @ResponseBody
    public Object getTime(HttpServletRequest request) throws IOException{
        Map<String, String> params = this.getParameterMap(request);
        log.info("getTime.request->"+params);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("flag","T");
        resultMap.put("dataTimeLong",DateUtils.Now.toLong());
        resultMap.put("dataTimeStr",DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        return resultMap;
    }

}


